package com.ruoyi.erp.controller;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.util.api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.erp.service.IBzFaCardsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资产增加Controller
 *
 * @author ztj
 * @date 2023-04-10
 */
@RestController
@RequestMapping("/erp/cards")
public class BzFaCardsController extends BaseController {
    @Autowired
    private IBzFaCardsService bzFaCardsService;
    @Autowired
    private api api;

    /**
     * 查询资产增加列表
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:list')")
    @GetMapping("/list")
    public TableDataInfo list(BzFaCards bzFaCards) {
        startPage();
        List<BzFaCards> list = bzFaCardsService.selectBzFaCardsList(bzFaCards);
        return getDataTable(list);

    }

    @PreAuthorize("@ss.hasPermi('erp:cards:list')")
    @GetMapping("/listErp")
    public TableDataInfo listErp(BzFaCards bzFaCards) {
        startPage();
        List<BzFaCards> list = bzFaCardsService.selectBzFaCardsListErp(bzFaCards);
        return getDataTable(list);

    }

    /**
     * 资产同步
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:add')")
    @Log(title = "资产同步", businessType = BusinessType.IMPORT)
    @GetMapping("/sync/{ids}")
    public AjaxResult faSync(@PathVariable Long[] ids) {
        List<BzFaCards> list = bzFaCardsService.selectBzFaCardsListErp(ids);
        AtomicBoolean isSyc = new AtomicBoolean(true);
        list.forEach(item -> {
            try {
                if (bzFaCardsService.insertBzFaCards(item) != 1) {
                    isSyc.set(false);
                }
            } catch (Exception e) {
                logger.error(e.toString());
            }
        });
        return toAjax(isSyc.get());
    }

    /**
     * 资产推送
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:add')")
    @Log(title = "资产推送", businessType = BusinessType.IMPORT)
    @GetMapping("/push/{ids}")
    public AjaxResult faPush(@PathVariable Long[] ids) {
        List<BzFaCards> list = bzFaCardsService.selectBzFaCardsList(ids);
//        BzFaCardsParam param = new BzFaCardsParam();
//        param.setBill_date(DateUtil.format(new Date(), "yyyy-MM-dd"));
//        param.setBill_iOptType("新增");
//        List<Bills> bills = new ArrayList<>();
//        Bills bill= new Bills();
//        bill.setBill_code(UUID.fastUUID().toString());
//        bill.setVouchers(BeanUtil.copyToList(list, Object.class));
//        bills.add(bill);
//        param.setBills(bills);
//        List<BzFaCardsPush> pushList = new ArrayList<>();
        list.forEach(item -> {
            BzFaCardsPush push = new BzFaCardsPush();
            push.setVoucherNo(item.getsCardID().toString());
            push.setAssetStyle(item.getsStyle());
            push.setAssetUseName(item.getsStatusID());
            push.setCategoryCode(item.getsTypeNum());
            push.setDepreMonth(item.getlLife().toString());
            push.setFullName(item.getsAssetName());
            push.setGetDate(DateUtil.format(item.getdStartdate(), "yyyy-MM-dd"));
            push.setInitialNumber(item.getsAssetNum());
            push.setLocationName(item.getsSite());
            DecimalFormat df1 = new DecimalFormat("#.00");
            push.setNetValue(df1.format(item.getDblBV()));
            push.setPolicyNo(item.getsCardNum());
            push.setQty("1");
            push.setTotalMoney(df1.format(item.getDblValue()));
            push.setUnitPrice(df1.format(item.getDblValue()));
            push.setUseDepartment(item.getsDeptNames());
            faPushHttp(push, item);
//            new Thread(() -> faPushHttp(push, item)).start();
        });
        return toAjax(1);
    }

    private void faPushHttp(BzFaCardsPush push, BzFaCards item) {
        Map<String, String> heads = new HashMap<>();
        heads.put("Content-Type", "application/json;charset=UTF-8");
        logger.debug(JSONUtil.toJsonStr(push));
        HttpResponse response = HttpRequest.post(api.getAddFa())
                .headerMap(heads, false)
                .body(JSONUtil.toJsonStr(push))
                .timeout(5 * 60 * 1000)
                .execute();
        logger.debug(response.body());
        ResultData resultData = JSONUtil.toBean(response.body(), ResultData.class);
        if (resultData.getErrorcode() == 0) {
            item.setIsPush(1);
        } else {
            item.setIsPush(3);
        }
        bzFaCardsService.updateBzFaCards(item);
    }

    @PostMapping("/pushNotice")
    public AjaxResult pushNotice(@RequestBody BzFaCardsParam param) {
        logger.debug(JSONUtil.toJsonStr(param));
        List<BzFaCards> returnNotice = new ArrayList<>();
        param.getBills().forEach(item -> {
            List<BzFaCards> list = BeanUtil.copyToList(item.getVouchers(), BzFaCards.class);
            list.forEach(cards -> {
                if (bzFaCardsService.updateBzFaCards(cards) == 1) {
                    returnNotice.add(cards);
                }
            });
        });

        return success(returnNotice);
    }

    /**
     * 导出资产增加列表
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:export')")
    @Log(title = "资产增加", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BzFaCards bzFaCards) {
        List<BzFaCards> list = bzFaCardsService.selectBzFaCardsList(bzFaCards);
        ExcelUtil<BzFaCards> util = new ExcelUtil<BzFaCards>(BzFaCards.class);
        util.exportExcel(response, list, "资产增加数据");
    }

    /**
     * 获取资产增加详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bzFaCardsService.selectBzFaCardsById(id));
    }

    /**
     * 新增资产增加
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:add')")
    @Log(title = "资产增加", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BzFaCards bzFaCards) {
        return toAjax(bzFaCardsService.insertBzFaCards(bzFaCards));
    }

    /**
     * 修改资产增加
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:edit')")
    @Log(title = "资产增加", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BzFaCards bzFaCards) {
        return toAjax(bzFaCardsService.updateBzFaCards(bzFaCards));
    }

    /**
     * 删除资产增加
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:remove')")
    @Log(title = "资产增加", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bzFaCardsService.deleteBzFaCardsByIds(ids));
    }
}
